import os

from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_job, register_events

from models.models import Advertisement, KnowledgeBase, GoodPicture

# 1.实例化调度器
scheduler = BackgroundScheduler(timezone="Asia/Shanghai")
scheduler.add_jobstore(DjangoJobStore(), "default")


# 不能使用@register_job装饰器方式，会导致 apscheduler.schedulers.SchedulerNotRunningError: Scheduler is not running
def clear():
    good_paths = [os.path.split(item)[1] for item in GoodPicture.objects.all().values_list('picture', flat=True)]
    ad_paths = [os.path.split(item)[1] for item in Advertisement.objects.all().values_list('picture', flat=True)]
    knowledge_paths = [os.path.split(item)[1] for item in KnowledgeBase.objects.all().values_list('file', flat=True)]
    good_exist_files = os.listdir("static/good/")
    ad_exist_files = os.listdir("static/ad/")
    knowledge_exist_files = os.listdir("static/knowledge/")
    for good_pic in good_exist_files:
        if good_pic not in good_paths:
            os.remove(os.path.join("static/good/", good_pic))
    for ad_pic in ad_exist_files:
        if ad_pic not in ad_paths:
            os.remove(os.path.join("static/ad/", ad_pic))
    for knowledge_pic in knowledge_exist_files:
        if knowledge_pic not in knowledge_paths:
            os.remove(os.path.join("static/knowledge/", knowledge_pic))


scheduler.add_job(clear, "cron", hour='0', minute='0', second='0', id="clear_file")
